'use strict'
var tenpay = require('tenpay');
var moment = require('moment')
module.exports = function* (ctx) {
    //这个接口的逻辑
    //首先接受前台POST发送的 Id和价格信息后  发送数据给微信服务端，微信服务端会返回一些支付订单数据  将数据记录到数据库中的用户订单信息表中后 把数据发送给前台 让前台调用支付API 完成支付
    var num = Date.parse(new Date()) / 1000;
    var rand = "";
    for (var i = 0; i < 3; i++) {
        var r = Math.floor(Math.random() * 10);

        rand += r;
    }
    var new_out_trade_no = num + "" + rand

    const openid = ctx.request.body.openid
    const price = ctx.request.body.price
    var config = {
        appid: 'wx75d670707d4a4b7a',
        mchid: '1462944002',
        partnerKey: 'QK6mob8LbXrbj8hJFvdb0kkmNGWJOex8',
        //pfx: require('fs').readFileSync('证书文件路径'),
       notify_url: "https://dev.zhuayuos.com/wechat"
       //notify_url: "http://zhoucanyu.iask.in/wechat"
        //spbill_create_ip: 'IP地址'
    }
    var api = new tenpay(config);
    var middleware = api.middleware();
    var order = {
        out_trade_no: new_out_trade_no,
        body: '测试',
        total_fee: price * 1,
        openid: openid
    }


    var result = yield api.getPayParams(order)
    result.timestamp = moment((result.timestamp + "") * 1000).format("YYYY-MM-DD HH:mm:ss")
    result.out_trade_no = new_out_trade_no;
    result.openID = openid
    result.total_fee = price
    const result_out_trade_no = yield ctx.service.pay.insert_out_trade_no_user(result)
    ctx.body = result

}